package com.meteor.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * 处理error异常
     */
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Model model, HttpServletRequest request, Exception e) throws Exception {
        logger.error("Request URL：{}, Exception：{}",request.getRequestURL(), e);
        //如果注解找到响应的状态码，则抛出404异常
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }
        model.addAttribute("url",request.getRequestURL());
        model.addAttribute("exception",e);
        return "error/error";
    }
}
